import asyncio
from playwright.async_api import async_playwright


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=False)
        page = await browser.new_page()

        # 在这里执行你的页面操作

        # 你的测试脚本完成后，保持事件循环运行
        await asyncio.Event().wait()


async def handle_browser_close(browser):
    print("浏览器已关闭")
    await browser.close()  # 关闭浏览器
    asyncio.get_running_loop().stop()  # 停止事件循环


async def run():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=False)
        # 监听浏览器关闭事件
        browser.on("close", lambda: asyncio.create_task(handle_browser_close(browser)))
        await main()


asyncio.run(run())
